<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
      
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="区域类型">
          <j-dict-select-tag  v-decorator="['districtType', {rules: [{ required: true, message: '请选择区域类型!' }]}]" placeholder="" :type="'radio'" :triggerChange="true" dictCode="district_type" @change="districtChange"/>
        </a-form-item>
        
        <a-form-item 
          label="所在地区" 
          :labelCol="labelCol" 
          :wrapperCol="wrapperCol"
          v-show="districtVisible">
          <a-cascader :options="provinceOptions" v-decorator="[ 'pcd', {rules: [{validator: this.validateDistrictType}]}]" @change="onDistrictChange" placeholder="请选择区域"/>
        </a-form-item>
      
        <a-form-item label="轮播图" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-upload
            listType="picture-card"
            class="avatar-uploader"
            :showUploadList="false"
            :action="uploadAction"
            :data="{'isup':1}"
            :headers="headers"
            :beforeUpload="beforeUpload"
            @change="handleChange"
          >
            <img v-if="picUrl" :src="getAvatarView()" alt="轮播图" style="height:104px;max-width:300px"/>
            <div v-else>
              <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
        </a-form-item>
        
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="banner链接">
          <a-input placeholder="请输入banner链接" v-decorator="['bannerLink', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="加油站主页">
          <a-input placeholder="请输入加油站主页" v-decorator="['oilHost', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="banner状态">
          <j-dict-select-tag  v-decorator="['status', {rules: [{ required: true, message: '请选择banner状态!'}] }]" placeholder="" :type="'radio'" :triggerChange="true" dictCode="banner_status" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="位置">
          <a-input-number v-decorator="[ 'bannerSort', {rules: [{ required: true, message: '请输入位置!' }]}]" />
        </a-form-item>
		
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import pick from 'lodash.pick'
  import moment from 'moment'
  import Vue from 'vue'
  // 引入搜索部门弹出框的组件
  import { ACCESS_TOKEN } from "@/store/mutation-types"
  import { httpAction } from '@/api/manage'
  import { provinceAll } from '@/api/api'

  export default {
    name: "BannerModal",
    data () {
      return {
        title:"操作",
        visible: false,
        districtVisible: false,
        uploadLoading: false,
        provinceOptions: [],
        picUrl: "",
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },

        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules:{
        },
        url: {
          fileUpload: window._CONFIG['domianURL']+"/sys/common/upload",
          imgerver: window._CONFIG['domianURL']+"/sys/common/view",
          add: "/lww/banner/add",
          edit: "/lww/banner/edit",
        },
        infoName:{
          provinceId: '',
          province: '',
          cityId: '',
          city: '',
          districtId: '',
          district: '',
        }
      }
    },
    created () {
      const token = Vue.ls.get(ACCESS_TOKEN);
      this.headers = {"X-Access-Token":token}
      this.initPprovince();
    },
    computed:{
      uploadAction:function () {
        return this.url.fileUpload;
      }
    },
    methods: {
      add () {
        this.picUrl = "";
        this.uploadLoading = false;
        this.edit({districtType:'0', status: '0'});
      },
      // 文件上传预览 start
      beforeUpload: function(file){
        var fileType = file.type;
        if(fileType.indexOf('image')<0){
          this.$message.warning('请上传图片');
          return false;
        }
        //TODO 验证文件大小
      },
      handleChange (info) {
        this.picUrl = "";
        if (info.file.status === 'uploading') {
          this.uploadLoading = true;
          return
        }
        if (info.file.status === 'done') {
          var response = info.file.response;
          this.uploadLoading = false;
          console.log(response);
          if(response.success){
            this.model.banner = response.message;
            this.picUrl = "Has no pic url yet";
          }else{
            this.$message.warning(response.message);
          }
        }
      },
      getAvatarView(){
        return this.url.imgerver +"/"+ this.model.banner;
      },
      initPprovince(){
        provinceAll().then(res=>{
          if(res.success){
            this.provinceOptions = res.result
          }
        })
      },
      edit (record) {
        this.form.resetFields();
        if(record.hasOwnProperty("id")){
          this.picUrl = "Has no pic url yet";
        }
        this.districtVisible = (record.districtType == 0 ? false : true);
        this.model = Object.assign({}, record);
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'districtType', 'banner','bannerLink','oilHost','pcd', 'status','bannerSort'))
		  //时间格式化
        });

      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            let formData = Object.assign(this.model, values);
            //时间格式化
            
            console.log(formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }
        })
      },
      handleCancel () {
        this.close()
      },
      districtChange(v) {
        this.districtVisible = (v == 0 ? false : true);
      },
      validateDistrictType(rule, value, callback){
        if(this.districtVisible && !value) {
          callback("请选择地区!");
        } else {
          callback();
        }
      },
      onDistrictChange(value) {
        const obj = this.provinceOptions.find(item => {
          return item.value === value[0]
        })
        this.infoName.province = obj.label
        this.infoName.provinceId = obj.value
        if(obj.children){
          const cityObj = obj.children.find(item => {
            return item.value === value[1]
          })
          this.infoName.city = cityObj.label
          this.infoName.cityId = cityObj.value
          if(cityObj.children){
            const districtObj = cityObj.children.find(item => {
              return item.value === value[2]
            })
            this.infoName.district = districtObj.label
            this.infoName.districtId = districtObj.value
          }
        }
        this.model = Object.assign(this.model, this.infoName);
      },
    }
  }
</script>

<style lang="less" scoped>

</style>